package com.ly.mpayment.rest.up.wswpay;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("wswpay")
public class WswpayRest {

        Logger logger = Logger.getLogger(WswpayRest.class);

        @Autowired
        IUporderService upOrderService;

        @Autowired
        IDownRechargeFlowService flowService;

        @Autowired
        IDownShopInfoService shopService;

        @Autowired
        IUpShopInfoService upShopInfoService;


        @Path("callBack")
        @POST
        public String callBack(@RequestBody String data) {
            logger.info("wswpay_callback:" + data);
            if (!StringUtils.isBlank(data)) {
                JSONObject multiMap = JSONObject.parseObject(data);
                UpOrder order = upOrderService.findById(multiMap.getString("orderid"));
                if(order == null){
                    logger.info("订单不存在:"+data);
                    return "订单不存在";
                }
                final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
                if(upShopInfo == null){
                    logger.info("渠道用户不存在:"+data);
                    return "failt";
                }

                //md5(key+parterid+id+orderid+account+amt+state+key)
                if(!multiMap.getString("sign").equals(MD5.md5(upShopInfo.getUpkey()+upShopInfo.getAppId()+multiMap.getString("id")+
                        multiMap.getString("orderid")+multiMap.getString("account")+multiMap.getString("amt")+
                        multiMap.getString("state")+upShopInfo.getUpkey()).toLowerCase())){
                    logger.info("签名错误:"+data);
                    return "0";
                }

                //0-充值成功，2-充值失败 100-充值失败
                if (order != null && multiMap.getString("state").equals("0") && order.getStatus() == Config.status[0]) {
                    order.setRemark(multiMap.containsKey("sernum") ? multiMap.getString("sernum") : "");
                    RechargeRest.successUpOrder.add(order);
                    return "success";
                } else if (order != null && order.getStatus() == Config.status[0] && (
                        multiMap.getString("state").equals("2") || multiMap.getString("state").equals("100")
                        )) {
                    order.setRemark("");
                    RechargeRest.failtUpOrder.add(order);
                    return "success";
                } else {
                    this.upOrderService.addOrderMsg(order,multiMap.getString("state"));
                    logger.info("xuanjie_not_found_order:" + multiMap.getString("state") + "," + (order == null ? "" : order.getUpphonenum()));
                }
            }
            return "0";
        }


        /**
         * 订单提交
         *
         * version 必须 版本号，当前为 1.0.1
         * parterid 必须 商户 ID 平台提供
         * orderid 必须 商户订单号（唯一、不可重复提交 最长 32 位）
         * account 必须 充值账号 amt 必须 充值金额 单位元
         * pid 必须 产品分类见附录一
         * cid 必须 产品分类见附录二
         * ts 必须 时间戳(格式：yyyyMMddHHmmss) 误差不超过 10 分钟
         * callbackurl 否 回调地址，(url-utf8 编码)
         * @param order
         * @param shop
         */
        public void commitOrder(UpOrder order, UpShopInfo shop) {

            JSONObject data = new JSONObject();
            data.put("version","1.0.1");
            data.put("parterid", shop.getAppId());
            data.put("orderid", order.getUporderuuid());
            data.put("account", order.getUpphonenum());
            data.put("amt", order.getUpShopPro().getUpfacevalue());
            //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
            //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
            //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
            data.put("pid", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "1" :
                    order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "2" :
                            order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "3" : 4);
            data.put("cid", 1);
            data.put("ts", new DateUtils().toTimeStamp());
            data.put("callbackurl", shop.getOrderCallAddress());

            //MD5 签名,key 由平台提供 md5(key+version+parterid+orderid+account+amt+pid+cid+ts+key)
            data.put("sign", MD5.md5(shop.getUpkey()+data.getString("version")+data.getString("parterid")+data.getString("orderid")+
                    data.getString("account")+data.getString("amt")+data.getString("pid")+data.getString("cid")+
                    data.getString("ts")+shop.getUpkey()));

            String result = HttpClient.post(shop.getOrderCommitAddress(),data.toString());
            logger.info("commitOrder_wswpay:" + result + ":" + StringSort.jsonToString(data));
            if (!StringUtils.isBlank(result)) {
                try{
                    JSONObject json = JSONObject.parseObject(result);
                    if (json.containsKey("code") && json.getString("code").equals("00000")) {
                        this.upOrderService.updateUpOrderMsg(order,json.getJSONObject("result").getString("id"),json.containsKey("msg") ?
                                json.getString("msg") : "");
                    } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                        order.setRemark(json.getString("msg"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        upOrderService.addOrderMsg(order, json.getString("msg"));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
                }
            } else {
                this.upOrderService.updateUpOrderArtificial(order, "","");
                logger.info("commitOrder_error:" + order.getUpphonenum());
            }
        }

        Set<String> errorCode = new HashSet<String>(){{
            add("10000");
            add("10001");
            add("10002");
            add("10003");
            add("10004");
            add("10005");
            add("10006");
            add("10007");
            add("10008");
            add("10009");
            add("10011");
        }};

        /**
         * 订单查询
         *
         * @param upOrder
         * @param shopInfo
         */
        public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
            JSONObject data = new JSONObject();
            data.put("version","1.0.1");
            data.put("orderid", upOrder.getUporderuuid());
            data.put("parterid", shopInfo.getAppId());
            data.put("ts", new DateUtils().toTimeStamp());
            //md5(key+version+parterid+orderid+ts+key)
            data.put("sign", MD5.md5(shopInfo.getUpkey()+data.getString("version")+data.getString("parterid")+
                    data.getString("orderid")+data.getString("ts")+shopInfo.getUpkey()));
            String result = HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
            logger.info("wswpay_queryOrder:" + StringSort.jsonToString(data) + ":" + result);
            if (!StringUtils.isBlank(result)) {
                JSONObject jsonD = JSONObject.parseObject(result);
                if (jsonD.containsKey("code") && jsonD.getString("code").equals("00000")) {
                    //state 1-充值中，0-充值成功，2-充值失败 100-充值失败
                    UpOrder order = upOrderService.findById(jsonD.getJSONObject("result").getString("orderid"));
                    if (order != null && jsonD.getJSONObject("result").getString("state").equals("0") && order.getStatus() == Config.status[0]) {
                        order.setRemark( jsonD.getJSONObject("result").containsKey("sernum") ? jsonD.getJSONObject("result").getString("sernum") :
                                jsonD.containsKey("msg") ? jsonD.getString("msg") : "");
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] &&
                            (jsonD.getJSONObject("result").getString("state").equals("2") ||
                             jsonD.getJSONObject("result").getString("state").equals("100") )) {
                        order.setRemark( jsonD.containsKey("msg") ? jsonD.getString("msg") : "");
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,jsonD.getString("msg"));
                        logger.info("wswpay_not_found_order:" + order.getUpphonenum());
                    }
                } else {
                    logger.info("wswpay_not_found_order:" + upOrder.getUpphonenum());
                }
            }
        }
    }
